package com.neudu.yiyang.intercepter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.utils.FLAGS;
import com.neudu.yiyang.utils.RedisUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

public class UserIntercepter implements HandlerInterceptor {
    @Autowired
    RedisUtils redisUtils; //这个东西需要 所在的拦截器 也注册进Spring成组件
                            //在注册的Config里查看

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws IOException {

        String wholePath = handler.toString();
        System.out.print("======拦截");
        System.out.print("["+wholePath.substring(wholePath.indexOf("#")+1)+"]");
        System.out.println("======");

        String token = req.getHeader("token");

        JSONReturn jsonReturn = new JSONReturn();

        if(token == null || token.trim().length() ==0){   // 401
            resp.getWriter().write(jsonReturn.returnFailed(FLAGS.NO_LOGIN));
            return false;
        }

        System.out.println(token);
        if (!redisUtils.hasKey(token)){
            resp.getWriter().write(jsonReturn.returnFailed(FLAGS.LOGIN_OUTOFTINE));
            return false;
        }

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("1231321321564654")).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
